package com.lagou.edu.controller;


import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lagou.edu.entity.MailReturn;
import com.lagou.edu.entity.TAuthCode;
import com.lagou.edu.feignservice.EmailService;
import com.lagou.edu.feignservice.UserService;
import com.lagou.edu.service.ITAuthCodeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author jobob
 * @since 2021-03-19
 */
@RestController
@RequestMapping("/code")
@Slf4j
@RefreshScope
public class TAuthCodeController {

    @Autowired
    private ITAuthCodeService itAuthCodeService;

    @Autowired
    private EmailService emailService;

    @Autowired
    private UserService userService;

    @Value("${authcode.expiretime}")
    private int expiretime = 60;

    /**
     * 生成注册码
     * @param email
     * @return
     */
    @GetMapping(value = "/create/{email}")
    public boolean createCode(@PathVariable("email") String email){
        //是否注册用户
        boolean registered = userService.isRegistered(email);
        if (registered) {
            return false;
        }

        //HuTool定义图形验证码的长和宽,验证码的位数，干扰线的条数
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(116, 36,4,10);
        TAuthCode tAuthCode = new TAuthCode();
        tAuthCode.setEmail(email);
        tAuthCode.setCode(lineCaptcha.getCode());
        tAuthCode.setCreatetime(DateUtil.date());
        tAuthCode.setExpiretime(DateUtil.offsetSecond(DateUtil.date(), expiretime));

        //删除之前存在的注册码
        QueryWrapper<TAuthCode> tAuthCodeQueryWrapper = new QueryWrapper<>();
        tAuthCodeQueryWrapper.eq("email" , email);
        itAuthCodeService.remove(tAuthCodeQueryWrapper);

        //插入注册码
        boolean b = itAuthCodeService.saveOrUpdate(tAuthCode);
        if (!b) {
            return false;
        }
        log.info("注册码：" + tAuthCode.getCode());

        //发邮件
        MailReturn mailReturn = emailService.sendEmail(email, lineCaptcha.getCode());
        return mailReturn.isSuccess();
    }

    /**
     * 校验验证码是否正确
     * @return 0正确1错误2超时
     */
    @GetMapping("/validate/{email}/{code}")
    public int validateCode(@PathVariable("email") String email, @PathVariable("code") String code){
        QueryWrapper<TAuthCode> tAuthCodeQueryWrapper = new QueryWrapper<>();
        tAuthCodeQueryWrapper.eq("email", email)
                .ge("expiretime", DateUtil.date());
        List<TAuthCode> list = itAuthCodeService.list(tAuthCodeQueryWrapper);
        if (list.size() == 0) {
            return 2;
        }
        for (TAuthCode tAuthCode : list) {
            if (tAuthCode.getCode().equalsIgnoreCase(code)) {
                return 0;
            }
        }
        return 1;
    }

    @GetMapping("/refresh")
    public String refresh(){
        String info = "注册吗超时时间：" + expiretime;
        log.info(info);
        return info;
    }
}
